/*
 * @描述: 安全设置页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { Form, Modal, List, Input, message } from 'antd';
import { connect } from 'dva';

const PasswordForm = Form.create()(
  class extends React.Component {
    constructor(props) {
      super(props);
      this.formLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 }
      };
    }
    render() {
      const { passwordVisible, onCancel, onOk, form } = this.props;
      const { getFieldDecorator } = form;
      const checkConfirm = (rule, value, callback) => {
        if (value && value !== form.getFieldValue('newPassword')) {
          callback(formatMessage({ id: 'validation.password.twice' }));
        } else {
          callback();
        }
      };
      return (
        <Modal
          destroyOnClose
          visible={passwordVisible}
          title={formatMessage({ id: 'app.settings.security.modify' })}
          okText={formatMessage({ id: 'app.common.confirm' })}
          onCancel={onCancel}
          onOk={onOk}
        >
          <Form>
            <Form.Item {...this.formLayout} key="oldPassword" label={formatMessage({ id: 'app.settings.security.oldpassword' })}>
              {getFieldDecorator('oldPassword', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.security.oldpassword.required' })
                  }
                ]
              })(
                <Input type="password" placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </Form.Item>
            <Form.Item {...this.formLayout} key="newPassword" label={formatMessage({ id: 'app.settings.security.newpassword' })}>
              {getFieldDecorator('newPassword', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.security.newpassword.required' })
                  }
                ]
              })(
                <Input type="password" placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </Form.Item>
            <Form.Item {...this.formLayout} key="confirmNewPassword" label={formatMessage({ id: 'app.settings.security.confirm-newpassword' })}>
              {getFieldDecorator('confirmNewPassword', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.security.confirm-newpassword.required' })
                  },
                  {
                    validator: checkConfirm
                  }
                ]
              })(
                <Input type="password" placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </Form.Item>
          </Form>
        </Modal>
      );
    }
  }
);

const MobileForm = Form.create()(
  class extends React.Component {
    render() {
      const { mobileVisible, onCancel, onOk, form, mobile } = this.props;
      return (
        <Modal
          destroyOnClose
          visible={mobileVisible}
          title={formatMessage({ id: 'app.settings.security.modify' })}
          okText={formatMessage({ id: 'app.common.confirm' })}
          onCancel={onCancel}
          onOk={onOk}
        >
          <Form>
            <Form.Item key="mobile" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.sysuser.mobile' })}>
              {form.getFieldDecorator('mobile', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.phone-number.required' })
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: formatMessage({ id: 'validation.phone-number.wrong-format' })
                  }
                ],
                initialValue: mobile
              })(
                <Input placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </Form.Item>
          </Form>
        </Modal>
      );
    }
  }
);

const EmailForm = Form.create()(
  class extends React.Component {
    render() {
      const { emailVisible, onCancel, onOk, form, email } = this.props;
      return (
        <Modal
          destroyOnClose
          visible={emailVisible}
          title={formatMessage({ id: 'app.settings.security.modify' })}
          okText={formatMessage({ id: 'app.common.confirm' })}
          onCancel={onCancel}
          onOk={onOk}
        >
          <Form>
            <Form.Item key="email" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.sysuser.email' })}>
              {form.getFieldDecorator('email', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.email.required' })
                  },
                  {
                    type: 'email',
                    message: formatMessage({ id: 'validation.email.wrong-format' })
                  },
                  {
                    max: 100,
                    message: formatMessage({ id: 'validation.email.length' })
                  }
                ],
                initialValue: email
              })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </Form.Item>
          </Form>
        </Modal>
      );
    }
  }
);

@connect(({ user }) => ({
  currentUser: user.currentUser
}))
class SecurityView extends Component {
  getData = () => {
    const { currentUser } = this.props;
    return [
      {
        title: formatMessage({ id: 'app.settings.security.password' }, {}),
        description: (
          <Fragment>
            {formatMessage({ id: 'app.settings.security.password-description' })}
          </Fragment>
        ),
        actions: [
          <a onClick={(values) => { this.showModal(values, 'password') }}>
            <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify" />
          </a>
        ]
      },
      {
        title: formatMessage({ id: 'app.settings.security.mobile' }, {}),
        description: `${formatMessage(
          { id: 'app.settings.security.mobile-description' },
          {}
        )}：${currentUser.mobile}`,
        actions: [
          <a onClick={(values) => { this.showModal(values, 'mobile') }}>
            <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify" />
          </a>
        ]
      },
      {
        title: formatMessage({ id: 'app.settings.security.email' }, {}),
        description: `${formatMessage(
          { id: 'app.settings.security.email-description' },
          {}
        )}：${currentUser.email}`,
        actions: [
          <a onClick={(values) => { this.showModal(values, 'email') }}>
            <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify" />
          </a>
        ]
      }
    ]
  };

  state = {
    passwordVisible: false,
    mobileVisible: false,
    emailVisible: false
  };

  showModal = (values, field) => {
    if (field === 'password') {
      this.setState({ passwordVisible: true });
    } else if (field === 'mobile') {
      this.setState({ mobileVisible: true });
    } else if (field === 'email') {
      this.setState({ emailVisible: true });
    }
  };

  handleCancel = (values, field) => {
    if (field === 'password') {
      this.setState({ passwordVisible: false });
    } else if (field === 'mobile') {
      this.setState({ mobileVisible: false });
    } else if (field === 'email') {
      this.setState({ emailVisible: false });
    }
  };

  handleUpdate = (values, field) => {
    const { currentUser, dispatch } = this.props;
    if (field === 'password') {
      const { form } = this.passwordFormRef.props;
      form.validateFields((err, fieldsValue) => {
        if (err) {
          return;
        }
        dispatch({
          type: 'account/updatePassword',
          payload: {
            password: fieldsValue.oldPassword,
            newPassword: fieldsValue.newPassword,
            id: currentUser.id
          }
        }).then(response => {
          if (response.message == 'success') {
            form.resetFields();
            this.setState({ passwordVisible: false });
            message.success(formatMessage({ id: 'app.settings.edit-success' }));
          } else {
            message.warning(response.message);
          }
        });
      });
    } else if (field === 'mobile') {
      const { form } = this.mobileFormRef.props;
      form.validateFields((err, fieldsValue) => {
        if (err) {
          return;
        }
        dispatch({
          type: 'account/updateSysUserInfo',
          payload: {
            fieldValue: fieldsValue.mobile,
            field: field,
            id: currentUser.id
          }
        }).then(response => {
          if (response.message == 'success') {
            form.resetFields();
            this.setState({ mobileVisible: false });
            message.success(formatMessage({ id: 'app.settings.edit-success' }));
            dispatch({
              type: 'user/fetchCurrent'
            });
          } else {
            message.warning(response.message);
          }
        });
      });
    } else if (field === 'email') {
      const { form } = this.emailFormRef.props;
      form.validateFields((err, fieldsValue) => {
        if (err) {
          return;
        }
        dispatch({
          type: 'account/updateSysUserInfo',
          payload: {
            fieldValue: fieldsValue.email,
            field: field,
            id: currentUser.id
          }
        }).then(response => {
          if (response.message == 'success') {
            form.resetFields();
            this.setState({ emailVisible: false });
            message.success(formatMessage({ id: 'app.settings.edit-success' }));
            dispatch({
              type: 'user/fetchCurrent'
            });
          } else {
            message.warning(response.message);
          }
        });
      });
    }
  };

  savePasswordFormRef = passwordFormRef => {
    this.passwordFormRef = passwordFormRef;
  };

  saveMobileFormRef = mobileFormRef => {
    this.mobileFormRef = mobileFormRef;
  };

  saveEmailFormRef = emailFormRef => {
    this.emailFormRef = emailFormRef;
  };

  render() {
    const { currentUser } = this.props;
    return (
      <Fragment>
        <List
          itemLayout="horizontal"
          dataSource={this.getData()}
          renderItem={item => (
            <List.Item actions={item.actions}>
              <List.Item.Meta title={item.title} description={item.description} />
            </List.Item>
          )}
        />
        <PasswordForm
          wrappedComponentRef={this.savePasswordFormRef}
          passwordVisible={this.state.passwordVisible}
          onCancel={(values) => { this.handleCancel(values, 'password') }}
          onOk={(values) => { this.handleUpdate(values, 'password') }} />
        <MobileForm
          wrappedComponentRef={this.saveMobileFormRef}
          mobileVisible={this.state.mobileVisible}
          onCancel={(values) => { this.handleCancel(values, 'mobile') }}
          onOk={(values) => { this.handleUpdate(values, 'mobile') }}
          mobile={currentUser.mobile} />
        <EmailForm
          wrappedComponentRef={this.saveEmailFormRef}
          emailVisible={this.state.emailVisible}
          onCancel={(values) => { this.handleCancel(values, 'email') }}
          onOk={(values) => { this.handleUpdate(values, 'email') }}
          email={currentUser.email} />
      </Fragment>
    );
  }
}

export default SecurityView;
